const request = require('request');
const config  = require('../config/config');

class merchant_word{
    constructor() {
    }

    async valid(cookie){
        //解析ubId
        let ubId = await this.parserCookiesByUbId(cookie);
        console.log(`ubId:${ubId}`)
        return new Promise((resolve, reject) => {
            let options = {
                url:'https://www.merchantwords.com/api/event',
                method:'POST',
                json:true,
                proxy:`http://${config.PROXY.HOST}:${config.PROXY.PORT}`,
                headers: {
                    "Cookie":cookie,
                    'origin':'https://www.merchantwords.com'
                },
                body:{"event":"page load","meta":"","ubId":ubId}
            };

            request(options,async(err,response,body) => {
                if(err){
                    console.log(`merchant_words cookie invalid. error:${JSON.stringify(err)}`);
                    if(err.code === 'ECONNRESET'){
                        resolve(true);
                    }else{
                        resolve(false);
                    }
                }else{
                    if(body.success && !body.success){
                        console.log(`merchant_words cookie invalid. Response:${JSON.stringify(body)}`);
                        resolve(false);
                    }else{
                        resolve(true)
                    }
                }
            })
        })
    }

    async parserCookiesByUbId(cookie){
        let cks = cookie.split(';');
        for(let ck of cks){
            let vs = ck.split('=');
            if(vs[0].replace(' ','') === 'ubId'){
                return vs[1];
            }
        }
        return undefined;
    }
}

module.exports = merchant_word;
